package com.zzq.my.jetpacks.jectpackapp.ui.act

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import by.kirich1409.viewbindingdelegate.viewBinding
import com.aisier.architecture.base.BaseActivity
import com.google.android.material.imageview.ShapeableImageView
import com.zzq.my.jetpacks.jectpackapp.R
import com.zzq.my.jetpacks.jectpackapp.adapter.ViewPager2BannerAdapter
import com.zzq.my.jetpacks.jectpackapp.databinding.ActivityViewpage2BannerBinding
import com.zzq.my.jetpacks.util.loadImage


/**
 * 描述：ViewPager2 轮播图
 * 作者：zhuangzeqin
 * 时间: 2022/1/18-17:04
 * 邮箱：zzq@eeepay.cn
 * 备注:
 */
class ViewPager2BannerAct : BaseActivity(com.zzq.my.jetpacks.jectpackapp.R.layout.activity_viewpage2_banner) {
    private lateinit var mViewPager2BannerAdapter: ViewPager2BannerAdapter
    private val vb by viewBinding(ActivityViewpage2BannerBinding::bind)
    private var currentPosition = 0
    /**
     * 初始化数据
     */
    override fun initData() {


    }

    /**
     * 初始化操作
     */
    @SuppressLint("ClickableViewAccessibility")
    override fun initView() {
        mViewPager2BannerAdapter = ViewPager2BannerAdapter()

        val newList = arrayListOf<String>()

        val listData = mutableListOf<String>()
        listData.apply {
            add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.tuguaishou.com%2Fips_templ_preview%2F2d%2Ff7%2F28%2Flg_2365780_1571050208_5da452e038da0.jpg%21w1024_w%3Fauth_key%3D2209921611-0-0-fd68fafb8c92300ff11e73e0a2a986c2&refer=http%3A%2F%2Fimg.tuguaishou.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673429260&t=9f3024459f23d6645a06d3d6b2efa9da")
            add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ffa0eb09da11899f9ebadfa5b24760f4a84befad11def6-jKbgux_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673429260&t=7bebb07369028196b39cd4f966b7e4ca")
            add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01e669572bfe806ac725381234430c.jpg%402o.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673429260&t=c3e08f33b62c2fa255d5d075f01b1263")
        }
        //数据源的第一位add最后一张图
        newList.add(listData[listData.size-1])
        for (item in listData) {
            newList.add(item)
        }
        newList.add(listData[0])

//        mViewPager2BannerAdapter.setList(listData)
        vb.vp2.apply {
            adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>(){

                override fun onCreateViewHolder(
                    parent: ViewGroup,
                    viewType: Int
                ): RecyclerView.ViewHolder {
//                    val view =
//                        LayoutInflater.from(parent.context).inflate(com.zzq.my.jetpacks.jectpackapp.R.layout.item_banner, parent, false)


                    val inflate: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.item_banner, null)

                    val layoutParams = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                    )

                    inflate.layoutParams = layoutParams
                    return object : RecyclerView.ViewHolder(inflate) {}
                }


                override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
                    holder.itemView.let {
                        val img = it.findViewById<ShapeableImageView>(R.id.banner_image)
                        img.loadImage(newList[position])
                    }
                }

                /**
                 * Returns the total number of items in the data set held by the adapter.
                 *
                 * @return The total number of items in this adapter.
                 */
                override fun getItemCount(): Int = newList.size

            }
            this.registerOnPageChangeCallback(object :ViewPager2.OnPageChangeCallback(){
                override fun onPageSelected(position: Int) {
                    currentPosition = position
                }

                override fun onPageScrollStateChanged(state: Int) {
                    super.onPageScrollStateChanged(state)
                    //只有在空闲状态，才让自动滚动
                    if (state == ViewPager2.SCROLL_STATE_IDLE)
                    {
                        if (currentPosition == 0) {
                            vb.vp2.setCurrentItem(mViewPager2BannerAdapter.itemCount - 2, false)
                        } else if (currentPosition == mViewPager2BannerAdapter.itemCount - 1) {
                            vb.vp2.setCurrentItem(1, false)
                        }

                    }
                }
            })
            //触摸暂停滚动
            /**
             * 我们知道触摸调用setOnTouchListener即可，但是给ViewPager2使用的时候你会发现不起作用。
            ViewPager2是一个视图组，未调用setOnTouchListener是因为recyclerview拦截事件并首先调用onTouchEvent
            bannerVp.getChildAt(0)给它设置监听即可
             */
            this.getChildAt(0).setOnTouchListener { _, event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        this.removeCallbacks(mLooper)
                    }
                    MotionEvent.ACTION_UP -> {
                        this.postDelayed(mLooper,1000)
                    }
                }
                return@setOnTouchListener false
            }
        }
    }

    private fun initViewPagerWithView()
    {

    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus){
            vb.vp2.postDelayed(mLooper,1000)
        }else{
            //失去焦点时移除
            vb.vp2.removeCallbacks(mLooper)
        }

    }

    private val mLooper = object : Runnable {
        override fun run() {
            vb.vp2.currentItem = ++vb.vp2.currentItem
            vb.vp2.postDelayed(this,1000)
        }
    }

    /**
     * 初始化点击事件操作
     */
    override fun eventOnClick() {

    }
}